package com.jsh.erp.service.examine;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsh.erp.datasource.entities.Examine;
import com.jsh.erp.datasource.entities.ExamineItem;
import com.jsh.erp.datasource.mappers.ExamineItemMapper;
import com.jsh.erp.exception.BusinessRunTimeException;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExamineItemServiceImpl extends ServiceImpl<ExamineItemMapper, ExamineItem> implements ExamineItemService {

    @Resource
    private ExamineService examineService;

    @Resource
    private ExamineItemMapper examineItemMapper;

    @Override
    public List<ExamineItem> selDataByDefaultNumber(String defaultNumber,String returnReason) {
        QueryWrapper<Examine> wrapper = new QueryWrapper<>();
        wrapper.eq("purchase_order_number", defaultNumber);
        wrapper.eq("return_reason",returnReason);
        List<Examine> examines = examineService.list(wrapper);
        if(examines.isEmpty()){
            throw new BusinessRunTimeException(500,"当前单据无质检单。");
        }
        List<ExamineItem> val = new ArrayList<>();
        for (Examine examine : examines) {
            List<ExamineItem> itemsVal = this.list(new QueryWrapper<ExamineItem>().eq("examine_id", examine.getId()));
            if(itemsVal.isEmpty()){
                throw new BusinessRunTimeException(500,"当前单据质检明细为空。");
            }
            oi:for (ExamineItem item : itemsVal) {
                item.setExamineQuantity(item.getExamineQuantity()-item.getUnqualifiedQuantity());
                for (ExamineItem item2 : val) {
                    if (item.getMaterialId().compareTo(item2.getMaterialId()) == 0) {
                        item2.setExamineQuantity(item2.getExamineQuantity()+item.getExamineQuantity());
                        item2.setUnqualifiedQuantity(item2.getUnqualifiedQuantity()+item.getUnqualifiedQuantity());
                        continue oi;
                    }
                }
                val.add(item);
            }
        }
        return val;
    }

    @Override
    public Long getExamineNumber(String number) {
        return examineItemMapper.getExamineNumber(number);
    }
}
